import '../../model/database.dart';
import '../../model/code_fragment.dart';
import 'package:sqliteasy_core/sqliteasy_core.dart';

class EntityInsertionAdapterGen {
  static CodeFragment gen(EntityInfo entityInfo, String statement) {
    final entityName = entityInfo.entityName;
    final className = "_${entityName}EntityInsertionAdapter";
    final bindStatement = StringBuffer();
    int paramIndex = 1;
    entityInfo.columns.forEach((element) {
      switch (element.type) {
        case SQLiteTypes.text:
          bindStatement.write("bindString(${paramIndex++}, entity.${element.field.name});");
          break;
        case SQLiteTypes.integer:
          bindStatement.write("bindInteger(${paramIndex++}, entity.${element.field.name});");
          break;
        case SQLiteTypes.real:
          bindStatement.write("bindDouble(${paramIndex++}, entity.${element.field.name});");
          break;
        case SQLiteTypes.blob:
          bindStatement.write("bindBlob(${paramIndex++}, entity.${element.field.name});");
          break;
      }
    });

    final content = """
class $className extends EntityInsertionAdapter<$entityName> {
  $className() : super("$statement");

  @override
  void bind($entityName entity) {
    $bindStatement
  }

}
    """;
    final codeFragment = CodeFragment(content, [
      "package:sqliteasy_core/sqliteasy_core.dart",
      entityInfo.location
    ]);
    return codeFragment;
  }
}
